#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
#include <cassert>
#include <cstdlib>
#include <ctime>
#include <queue>

#define N 1003
#define M 100000

using namespace std; 

struct pnt_t {
	int i, j; 
}; 

int n, m; 

char a[N][N]; 
int  b[N][N]; 	// 1: 			it has been added to queue. 
				// [2...n): 	the steps_id

int  g_steps[N*N]; 
int  step_id=1; 

pnt_t p[M]; 

int walk(int pi, int pj)
{
	queue<pnt_t> q; 
	pnt_t x, y; 
	int i; 
	pnt_t dir[] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; 
	int steps = 0; 
	
	x.i = pi; 
	x.j = pj; 
	if (g_steps[b[x.i][x.j]]>0) {
		return g_steps[b[x.i][x.j]]; 
	}

	q.push(x); 
	b[x.i][x.j] = 1; 
	step_id++; 
	while(!q.empty()) {
		x = q.front(); 
		q.pop(); 
		steps ++; 
		b[x.i][x.j] = step_id; 
		for (i=0; i<4; i++) {
			y.i = x.i + dir[i].i; 
			y.j = x.j + dir[i].j; 
			if (a[y.i][y.j]=='\0') {
				continue; 
			}
			if (b[y.i][y.j]>=1) {
				continue; 
			}
			if (a[y.i][y.j]==a[x.i][x.j]) {
				continue; 
			}
			q.push(y); 
			b[y.i][y.j] = 1; 
		}
	}
	g_steps[step_id] = steps; 
	return steps; 
}

int main()
{
	int i;
	
	//freopen("p1141.in", "r", stdin); 
	
	scanf("%d %d\n", &n, &m); 
	//printf("n=%d, m=%d\n", n, m); 
	for (i=1; i<=n; i++) {
		scanf("%s\n", &a[i][1]); 
	//	printf("s=[%s]\n", &a[i][1]); 
	}
	//printf("\n-----\n"); 
	for (i=0; i<m; i++) {
		scanf("%d %d", &p[i].i, &p[i].j);
	//	printf("%d %d\n", p[i].i, p[i].j);
	}

	for (i=1; i<=n; i++) {
		for (int j=1; j<=n; j++) {
			if (b[i][j]==0) {
				walk(i, j); 
			}
		}
	}

	for (i=0; i<m; i++) {
		cout<<g_steps[b[p[i].i][p[i].j]]<<endl;
	}
/*
	printf("\n-----\n"); 
	for (i=1; i<=n; i++) {
		for (int j=1; j<=n; j++) 
			printf("%2d ", b[i][1]); 
		printf("\n"); 
	}
*/

	return 0; 
}


